package cn.yj.netty.message.eventshander;

import cn.yj.netty.support.test.MessageProtocol;
import cn.yj.netty.utils.SpringBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 工厂创建 具体的业务处理Handler选择工厂
 * @author 永健
 * @since 2022-02-15 17:48
 */
@Component
public class MessageHandlerFactory implements BeanPostProcessor {
    private static final HashMap<String, MessageHandler> HANDLER_HASH_MAP = new HashMap<>();
    private static final List<MessageHandler> HANDLER_LIST = new ArrayList<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MessageHandler) {
            // this.registerHandler(beanName, handler);
            MessageHandler handler = (MessageHandler) bean;
            HANDLER_LIST.add(handler);
        }
        return bean;
    }

    public static MessageHandlerFactory getFactory() {
        return SpringBean.getBean(MessageHandlerFactory.class);
    }

    //    public void registerHandler(String name, MessageHandler handler) {
    //        HANDLER_HASH_MAP.put(name, handler);
    //    }

    //    public void registerHandler(MessageHandler handler) {
    //        HANDLER_LIST.add(handler);
    //    }

    public MessageHandler getHandler(MessageProtocol messageProtocol) {
        //return HANDLER_HASH_MAP.get(messageProtocol.getHeader().getCommandCode());
        for (MessageHandler handler : HANDLER_LIST) {
            if (handler.support(messageProtocol)) {
                return handler;
            }
        }
        return null;
    }


}
